<template>
  <div class="check">
    <div class="back_area">
      <div class="back_icon" @click="$parent.moudleChange(true)" />
      <div class="hover_underLine" @click="$parent.moudleChange(true)">报告列表</div>
      <div style="margin: 0 12px;">></div>
      <div class="hover_underLine">报告详情</div>
    </div>
    <div class="check_area">
      <div v-loading="loading1" class="reported_by checkCard">
        <div class="info">
          <div>
            <div style="margin-bottom: 12px;">汇报人：<span class="bold">{{ detail.reportaccount ? detail.reportaccount.real_name : '' }}</span></div>
            <div>{{ detail.group ? detail.group.name : '' }}<span>｜</span>{{ detail.create_time }}</div>
          </div>
          <div class="score">{{ detail.review ? detail.review.score || '--' : '--' }}</div>
        </div>
        <div class="body">
          <div class="summary">
            <div class="bold">总结</div>
            <div class="content" v-html="detail.conclusion" />
          </div>
          <div class="photo">
            <div class="bold">图片</div>
            <div class="photos">
              <viewer :images="detail.conclusion_picture">
                <img v-for="item in detail.conclusion_picture" :key="item" :src="'https://' + item">
              </viewer>
              <!-- <img v-for="item in detail.conclusion_picture" :key="item" :src="'https://' + item" alt="" @click="handlePictureCardPreview({url: 'https://' + item})"> -->
            </div>
          </div>
        </div>
        <div v-if="myInfo.role_id !== 100003 && !onlyCheck" class="footer">
          <el-button v-if="!unNext && !clickLast" type="primary" @click="nextOne">下一条</el-button>
          <el-button v-else type="primary" @click="back">返回</el-button>
          <div class="star_area" @click="setStar(detail)">
            <div :class="detail.is_star === 1 ? 'isStar_icon' : 'unStar_icon'" />
            <div style="margin-left: 10px;">{{ detail.is_star === 1 ? '已收藏' : '收藏' }}</div>
          </div>
        </div>
      </div>

      <!-- 点评 -->
      <div v-if="(myInfo.role_id !== 100003 && !onlyCheck) || reviewed" v-loading="loading2" class="checkCard">
        <div v-if="reviewed && !editing">
          <div class="info">
            <div>
              <div style="margin-bottom: 12px;">点评人：<span class="bold">{{ detail.review ? detail.review.reviewaccount.real_name : '' }}</span></div>
              <div>{{ detail.group ? detail.group.name : '' }}<span>｜</span>{{ detail.review ? detail.review.create_time : '' }}</div>
            </div>
          </div>
          <div class="body">
            <div class="summary">
              <div class="bold">总结</div>
              <div class="content" v-html="detail.review ? detail.review.review : ''" />
            </div>
            <div class="photo">
              <div class="bold">图片</div>
              <div class="photos">
                <viewer :images="detail.review.review_picture ? detail.review.review_picture : []">
                  <img v-for="item in detail.review.review_picture ? detail.review.review_picture : []" :key="item" :src="'https://' + item">
                </viewer>
                <!-- <img v-for="item in detail.review.review_picture ? detail.review.review_picture : []" :key="item" :src="'https://' + item" alt="" @click="handlePictureCardPreview({url: 'https://' + item})"> -->
              </div>
            </div>
          </div>
        </div>
        <div v-else class="editor">
          <div class="text_editor">
            <div class="bold" style="margin-bottom: 20px;">点评</div>
            <editor v-model="editorValue" />
          </div>
          <div class="photo">
            <div class="bold">图片</div>
            <div class="upload">
              <el-upload
                ref="fileUpload"
                action=""
                list-type="picture-card"
                :auto-upload="false"
                :accept="fileUtils.accept[1]"
                :file-list="uploadFilesList"
                :limit="9"
                :on-change="handleChange"
                :on-remove="handleRemove"
                :on-exceed="uploadImgExceed"
              >
                <i slot="default" class="el-icon-plus" />
                <div slot="file" slot-scope="{file}">
                  <viewer ref="viewer" :images="detail.conclusion_picture">
                    <img
                      class="el-upload-list__item-thumbnail"
                      :src="file.url"
                      alt=""
                    >
                  </viewer>
                  <span class="el-upload-list__item-actions">
                    <span
                      class="el-upload-list__item-preview"
                      @click="handlePictureCardPreview(file)"
                    >
                      <i class="el-icon-zoom-in" />
                    </span>

                    <span
                      v-if="!disabled"
                      class="el-upload-list__item-delete"
                      @click="handleRemove(file)"
                    >
                      <i class="el-icon-delete" />
                    </span>
                  </span>
                </div>
              </el-upload>
            </div>
          </div>
          <div class="score">
            <div class="label bold">点评分数:</div>
            <el-input
              v-model="score"
              style="width: 200px"
              type="text"
              placeholder="请输入点评分数"
            />
          </div>
        </div>
        <div v-if="myInfo.role_id !== 100003" class="footer">
          <el-button v-if="reviewed && !editing" type="primary" :loading="loading1" @click="editRevie">修改点评</el-button>
          <el-button v-if="!reviewed || editing" class="saveRevie" :loading="loading2" @click="submitReview(1)">保存</el-button>
          <el-button v-if="!reviewed || editing" type="primary" :loading="loading2" @click="submitReview(2)">提交点评</el-button>
        </div>
      </div>
    </div>
    <el-dialog :visible.sync="dialogVisible" width="640px">
      <img ref="previewImg" style="max-width: 600px;" :src="dialogImageUrl" alt="">
    </el-dialog>
  </div>
</template>

<script>
import { mapState } from 'vuex'
import { extname } from '@/utils'
import { fileUtils } from '@/utils/fileType'
import { report_detail, report_review, report_next, report_setstar } from '@/api/report'
import editor from '@/components/editor/index.vue'
import SHA256 from 'crypto-js/sha256'
import cosUploadTraverse from '@/utils/cosUploadTraverse'

export default {
  name: 'Check',
  components: { editor },
  props: {
    checkData: {
      type: Object,
      default() {
        return {}
      }
    },
    clickLast: {
      type: Boolean,
      default: false
    },
    reqParams: {
      type: Object,
      default() {
        return {}
      }
    },
    onlyCheck: {
      type: Boolean,
      default: false
    }
  },
  data() {
    // 这里存放数据
    return {
      fileUtils,
      loading1: false,
      loading2: false,
      dataList: [],
      detail: {
        review: {
          reviewaccount: {
            real_name: ''
          },
          review_picture: []
        },
        reportaccount: {}
      },
      uploadFilesList: [],
      dialogImageUrl: '',
      dialogVisible: false,
      checkStatus: 1,
      editorValue: '',
      disabled: false,
      alreadyExistUrl: [],
      reviewed: false,
      editing: false,
      unNext: false,
      score: ''
    }
  },
  computed: {
    ...mapState({
      myInfo: (state) => state.basicSettings.myInfo
    })
  },
  // 监控data中的数据变化
  watch: {},
  // 生命周期 - 创建完成（可以访问当前this实例）
  async created() {

  },
  // 生命周期 - 挂载完成（可以访问DOM元素）
  mounted() {
    console.log(this.onlyCheck)
    this.loadReportDetail(this.checkData.id)
  },
  // 生命周期 - keep-alive
  async activated() {

  },
  // 方法集合
  methods: {
    async loadReportDetail(id) {
      try {
        this.loading1 = true
        this.loading2 = true
        const { code, data } = await report_detail(id, { with: ['review.reviewaccount', 'reportaccount', 'group'] })
        if (!code) {
          this.detail = data
          this.reviewed = data.status === 1
          if (data.review && data.review.review_status) {
            this.reviewed = true
          }
        }
      } catch (error) {
        console.error(error)
      } finally {
        this.loading1 = false
        this.loading2 = false
      }
    },
    async setStar(data) {
      try {
        this.loading = true
        const { code } = await report_setstar(data.id, { is_star: data.is_star === 1 ? 2 : 1 })
        if (!code) {
          this.$messageOnce.success(data.is_star === 1 ? '取消收藏成功' : '设置收藏成功')
          this.loadReportDetail(data.id)
        }
      } catch (error) {
        console.error(error)
      } finally {
        this.loading = false
      }
    },
    back() {
      this.$parent.moudleChange(true)
    },
    async nextOne() {
      if (this.editing) {
        this.$messageOnce.warning('请先保存或提交点评内容')
        return
      }
      try {
        this.loading1 = true
        this.loading2 = true
        const { code, data } = await report_next(this.detail.id, this.reqParams)
        if (!code) {
          if (data) {
            if (data.status === 1) {
              this.reviewed = true
            } else {
              this.reviewed = false
              this.uploadFilesList = []
              this.editorValue = ''
            }
            if (data.is_last) {
              this.$messageOnce.warning('已经到底了')
              this.unNext = data.is_last
            }
            this.detail = data
          } else {
            this.unNext = true
            this.$messageOnce.warning('已经到底了')
          }
        }
      } catch (error) {
        console.error(error)
      } finally {
        this.loading1 = false
        this.loading2 = false
      }
    },
    async postReview(review_status, countConf) {
      try {
        this.loading2 = true
        const { successList } = countConf
        const newUploadList = successList.map((val) => {
          return val.sourceUrl
        })
        const review_picture = this.alreadyExistUrl.concat(newUploadList)
        const param = {
          review_status: review_status,
          review: this.editorValue,
          score: this.score,
          review_picture
        }
        const { code } = await report_review(this.detail.id, param)
        if (!code) {
          this.reviewed = true
          this.editing = false
          this.alreadyExistUrl = []
          this.loadReportDetail(this.detail.id)
          this.$messageOnce.success(review_status === 1 ? '保存成功！' : '点评成功！')
        }
      } catch (error) {
        console.error(error)
      } finally {
        this.loading2 = false
      }
    },
    editRevie() {
      this.editing = true
      this.uploadFilesList = []
      for (let i = 0; i < this.detail.review.review_picture.length; i++) {
        this.uploadFilesList.push({
          name: this.detail.review.review_picture[i],
          url: 'https://' + this.detail.review.review_picture[i]
        })
      }
      // this.uploadFilesList =
      this.score = this.detail.review.score
      this.editorValue = this.detail.review.review
    },
    submitReview(review_status) {
      this.handleFileList(review_status)
    },
    // 对预览文件进行处理
    async handleFileList(review_status) {
      // 对文件进行计算，hash256为文件名称
      const fileList = await this.handleSha245FileName()

      // 队列上传
      const countConf = await cosUploadTraverse(fileList)
      // 证明文件没有错误
      if (countConf.fail === 0) {
        await this.postReview(review_status, countConf)
      } else {
        // 证明上传文件有出错
        this.$messageOnce({
          message: '图片上传失败',
          type: 'error',
          duration: 2000
        })
      }
    },
    // 实现缩略图模板时删除文件
    handleRemove(file) {
      const fileList = this.$refs.fileUpload.uploadFiles
      const index = fileList.findIndex(fileItem => {
        return fileItem.uid === file.uid
      })
      fileList.splice(index, 1)
      this.uploadFilesList.splice(index, 1)
      // 删除data里面的数据
      // this.uploadFilesList.splice(
      //   this.uploadFilesList.indexOf(file.uid, 1) // 在上传文件列表中删除这个文件
      // )
    },
    formatExistUrl(list) {
      const unExistList = []
      for (let i = 0; i < list.length; i++) {
        if (list[i].raw) {
          unExistList.push(list[i])
        } else {
          this.alreadyExistUrl.push(list[i].url.replace('https://', ''))
        }
      }
      return unExistList
    },
    //  const fileList = this.formatExistUrl(this.uploadFilesList)
    async handleSha245FileName() {
      const fileList = this.formatExistUrl(this.uploadFilesList)
      const signedFileList = await Promise.all(
        fileList.map((val, index) => {
          return new Promise((resolve, reject) => {
            const fileType = extname(val.name)
            const reader = new FileReader()
            reader.readAsDataURL(val.raw)
            reader.onload = () => {
              const result = reader.result
              const signData = SHA256(result).toString()

              val.name = `${signData}.${fileType}`
              resolve(val)
            }
          })
        }))
      return await signedFileList
    },
    handlePictureCardPreview(file) {
      this.$refs.viewer.$viewer.show()
      // this.dialogImageUrl = file.url
      // this.dialogVisible = true
    },
    handleChange(file, fileList) {
      if (fileList.length > 9) {
        return false
      }
      this.uploadFilesList = fileList
    },
    uploadImgExceed() {
      this.$messageOnce({
        message: '最多只能上传9张图片',
        type: 'warning',
        center: true,
        offset: 100
      })
    }
  },
  // 进入页面前
  beforeRouteEnter(to, from, next) {
    next(vm => {

    })
  },
  // 离开页面前
  beforeRouteLeave(to, from, next) {
    next()
  }
}
</script>

<style lang="scss" scoped>
 @import "~@/styles/mixin.scss";
.check{
  margin: 17px 30px 0 32px;
  background-color: #f6f6f6;
  .back_area{
    height: 16px;
    font-size: 16px;
    font-family: SourceHanSansCN-Medium, SourceHanSansCN;
    font-weight: 500;
    color: #000000;
    line-height: 16px;
    margin-bottom: 17px;
    display: flex;
    .back_icon{
      width: 22px;
      height: 16px;
      background: url('../../assets/back_icon.png');
      background-size: 100%;
      margin-right: 12px;
      &:hover{
        cursor: pointer;
      }
    }
  }
  .reported_by{
    margin-right: 38px;
  }
  .check_area{
    min-height: 820px;
    display: flex;
    .checkCard{
      width: 750px;
      background: #FFFFFF;
      box-shadow: 0px 2px 40px 0px rgba(0, 0, 0, 0.05);
      .info{
        width: 100%;
        height: 100px;
        padding: 24px 30px;
        border-bottom: 1px solid #E4E4E4;
        font-size: 14px;
        font-family: SourceHanSansCN-Normal, SourceHanSansCN;
        font-weight: 400;
        color: #666666;
        line-height: 14px;
        display: flex;
        justify-content: space-between;
        .score {
          text-align: center;
          width: 60px;
          height: 60px;
          background: url('../../assets/report/score.png');
          background-size: 100%;
          font-size: 22px;
          font-family: SourceHanSansCN-Medium, SourceHanSansCN;
          font-weight: 500;
          color: #0E9700;
          line-height: 60px;
        }
      }
      .editor{
        height: 770px;
        overflow: auto;
        .text_editor{
          padding: 30px;
        }
        .photo{
          padding: 0 30px 30px 30px;
          .upload{
            padding: 30px 20px 0 20px;
            height: 140px;
            overflow: auto;
          }
        }
        .score {
          padding: 0 30px 30px 30px;
          display: flex;
          align-items: center;
          .label {
            width: 90px;
          }
        }
      }
      .body{
        height: 670px;
        overflow: auto;
        .summary{
          padding: 30px;
          font-size: 14px;
          font-family: SourceHanSansCN-Normal, SourceHanSansCN;
          font-weight: 400;
          color: #333333;
          line-height: 26px;
          .content{
            height: 300px;
            margin-top: 12px;
            padding-left: 20px;
            overflow: auto;
          }
        }
        .photo{
          padding: 0 30px 50px 30px;
          .photos{
            padding: 30px 20px 0 20px;
            height: 200px;
            overflow: auto;
            img{
              width: 124px;
              height: 124px;
              margin-right: 20px;
              object-fit: cover;
              cursor: pointer;
            }
          }
        }
      }
      .footer{
        width: 750px;
        height: 70px;
        text-align: center;
        box-shadow: 0px 2px 40px 0px rgb(0 0 0 / 5%);
        padding: 15px 30px;
        background-color: #fff;
        z-index: 9;
        .saveRevie {
          min-width: 100px;
          border-color: #fff;
          background: #F7F7F7;
        }
        .star_area {
          cursor: pointer;
          float: right;
          display: flex;
          align-items: center;
          font-size: 14px;
          font-family: SourceHanSansCN-Normal, SourceHanSansCN;
          font-weight: 400;
          color: #666666;
          padding: 10px 0;
        }
      }
    }
  }
}

.isStar_icon{
  width: 22px;
  height: 20px;
  background: url('../../assets/report/is_star.png');
  background-size: 100%;
  margin: 0 auto;
  cursor: pointer;
}

.unStar_icon{
  width: 22px;
  height: 20px;
  background: url('../../assets/report/un_star.png');
  background-size: 100%;
  margin: 0 auto;
  cursor: pointer;
}

.bold{
  font-size: 16px;
  font-family: SourceHanSansCN-Medium, SourceHanSansCN;
  font-weight: 500;
  color: #000000;
  line-height: 24px;
}

.hover_underLine:hover{
  text-decoration: underline;
  cursor: pointer;
}

::v-deep .el-upload--picture-card{
  width: 68px;
  height: 68px;
  line-height: 68px;
  background-color: #F7F7F7;
}

::v-deep .el-upload--picture-card:hover {
  .el-icon-plus {
    color: $MainColor;
  }
}

::v-deep .el-upload--picture-card i {
  position: relative;
  top: 2px;
}

::v-deep .el-upload-list--picture-card .el-upload-list__item{
  width: 68px;
  height: 68px;
}

.content ::v-deep img {
  max-width: 655px;
}
</style>
